import React, { PureComponent } from 'react';
import { Table, Card, Form, Input, Button, Tree, Pagination, Row, Col, message, Modal } from 'antd'
import { PageContainer } from '@ant-design/pro-layout'
import { getSubject,getAllSubject } from '@/services/lessons';
import AddModal from './AddModal';
import EditModal from './EditModal';
import Authorized from '@/components/Authorized/Authorized'
import { getMaterialList, deleteCourseware } from '@/services/learn'
import { fileurl} from '@/services/baseurl'
import {hasIsSw} from '@/utils/utils' 
export default class Index extends PureComponent<any, any> {
    constructor(props: any) {
        super(props)
        this.state = {
            treeData: [],
            options: [],
            showAdd: false,
            showEdit: false,
            count: 1,
            data: [],
            doc: [],
            cover: [],
            docs: '',
            covers: '',
            subject: [],
            subjectValue:'',
            sort: '0',
            name: '',
            id: '',
            searchSubject: [],
            searchName: '',
            currentPage: '1',
            is_jc:0
        }
    }
    showAdd = () => {
        this.setState({
            showAdd: true
        })
    }
    hideAdd = () => {
        this.setState({
            showAdd: false
        })
    }
    showEdit = (row: any) => {
        const subject=  row.subject.split(',').map(Number)
        const subjectValue= subject.length>2?[subject[0]]:subject
        this.setState({
            showEdit: true,
            doc: [
                {
                    uid: row.id,
                    name: row.name,
                    status: 'done',
                    url:  row.doc,
                    thumbUrl:  row.doc,
                },
            ],
            cover: [
                {
                    uid: row.id,
                    name: '封面图片',
                    status: 'done',
                    url: fileurl(row.is_jc) + row.cover,
                    thumbUrl: fileurl(row.is_jc) + row.cover,
                },
            ],
            docs: row.doc,
            covers: row.cover,
            subject,
            subjectValue,
            sort: row.sort,
            name: row.name,
            is_jc:row.is_jc,
            id: row.id
        })
    }
    hideEdit = () => {
        this.setState({
            showEdit: false
        })
    }
    changeSubject = (e: any,subject:any) => {
        let newarr = [];
        let getValue = (arr) => {
            for (let i = 0; i < arr.length; i++) {
                const item = arr[i];
                newarr.push(item.value)
                if(item.children[0]){
                    getValue(item.children)
                }
            }
        }
        if(!e[1]){
            getValue(subject)
        }else{
            newarr.push([...e])
        }
        this.setState({
            subject: newarr,
            subjectValue:e
        })
    }
    changeInputValue = (e: any, name: string) => {
        this.setState({
            [name]: e.target.value
        })
    }
    changeFile = (info: any, name: string) => {
        let fileList = [...info.fileList];
        fileList = fileList.slice(-1);
        fileList = fileList.map(file => {
            if (file.response) {
                file.url = file.response.url;
            }
            return file;
        });
        this.setState({ [name]: fileList });
    };

    getList = (page: string, subject: any) => {
        const { searchName } = this.state;
        getMaterialList({ page, name: searchName, subject }).then(res => {
            if(!res)return
            this.setState({
                count: res.count,
                data: res.data
            })
        })
    }
    changePage = (e: any) => {
        this.setState({
            currentPage: e
        })
        const { searchSubject } = this.state;
        this.getList(e, searchSubject)
    }
    changeSearchSubject = (e: any) => {
        this.setState({
            searchSubject: e,
            currentPage:'1'
        })
        const { currentPage } = this.state;
        this.getList(currentPage, e)
    }
    searchHandle = () => {
        const { currentPage, searchSubject } = this.state;
        this.getList(currentPage, searchSubject)
        this.setState({
            currentPage:1
        })
    }
    deleteHandle = (id: any) => {
        Modal.confirm({
            title: '提示',
            content: '确认删除该课件？',
            onOk: () => {
                deleteCourseware({
                    id
                }).then(res => {
                    if (res.status === 1) {
                        message.success('已删除');
                        this.searchHandle();
                    } else {
                        message.error('删除失败')
                    }
                })
            }
        })

    }
    componentDidMount() {
        this.getList('1', [])
        if(hasIsSw()){
            getAllSubject('2').then(res=>{
                getAllSubject('1').then(response=>{
                    if ((!res || !res[0])&&(!response||!response[0])) return;
                    const list = res.concat(response)
                    let data = JSON.stringify(list);
                    let data2 = JSON.stringify(list);
                    data = data.replace(/id/g, 'key').replace(/pkey/g, 'pid');
                    data2 = data2
                        .replace(/id/g, 'value')
                        .replace(/title/g, 'label')
                        .replace(/pvalue/g, 'pid');
                    this.setState({
                        treeData: JSON.parse(data),
                        options: JSON.parse(data2),
                    });
                })
            })
        }else{
            getSubject().then((res) => {
                if (!res || !res[0]) return;
                let data = JSON.stringify(res);
                let data2 = JSON.stringify(res);
                data = data.replace(/id/g, 'key').replace(/pkey/g, 'pid');
                data2 = data2
                    .replace(/id/g, 'value')
                    .replace(/title/g, 'label')
                    .replace(/pvalue/g, 'pid');
                this.setState({
                    treeData: JSON.parse(data),
                    options: JSON.parse(data2),
                });
            });
        }
    }

    render() {
        const { treeData, options, showAdd, showEdit, count, data, doc, cover, subjectValue,subject, sort, name, id, docs, covers,
            searchSubject, searchName, currentPage ,is_jc} = this.state;
        const columns = [
            {
                title: '封面',
                dataIndex: 'cover',
                render: (cover: string,row:any) => {
                    const str = fileurl(row.is_jc) + cover
                    return <img src={str} onClick={() => window.open(str)} style={{ height: 100, width: 100, objectFit: 'cover' }} alt=" " />
                }
            },
            {
                title: '课件名称',
                dataIndex: 'name'
            },
            {
                title: '所属科目',
                dataIndex: 'subjects',
                render:(subjects:string)=>{
                    return subjects?subjects.substr(0,subjects.length-1):''
                }
            },
            {
                title: '编辑日期',
                dataIndex: 'created_at'
            },
            // {
            //     title: '浏览次数',
            //     dataIndex: 'read'
            // },
            {
                title: '操作',
                dataIndex: 'id',
                render: (id: any, row: any) => {
                    return <React.Fragment>
                        <Authorized authority={[402]}>
                            <a style={{ marginRight: 30 }} onClick={() => this.showEdit(row)}>编辑</a>
                        </Authorized>
                        <Authorized authority={[403]}>
                            <a onClick={() => this.deleteHandle(id)}>删除</a>
                        </Authorized>
                    </React.Fragment>
                }
            },
        ]
        return (
            <PageContainer>
                <Card>
                    <Row>
                        <Col span={5}>
                            <Tree treeData={treeData} onSelect={this.changeSearchSubject} />
                        </Col>
                        <Col span={19}>
                            <div style={{ overflow: 'hidden', marginBottom: 20 }}>
                                <Form layout="inline" style={{ float: 'right' }}>
                                    <Form.Item>
                                        <Input placeholder="请输入搜索名称" onChange={(e) => this.changeInputValue(e, 'searchName')}></Input>
                                    </Form.Item>
                                    <Form.Item><Button type="primary" onClick={this.searchHandle}>查询</Button></Form.Item>
                                    <Authorized authority={[401]}>
                                        <Form.Item><Button type="primary" danger onClick={this.showAdd}>添加</Button></Form.Item>
                                    </Authorized>
                                </Form>
                            </div>
                            <Table columns={columns} pagination={false} dataSource={data} rowKey="id" />
                            <Pagination current={currentPage*1} showSizeChanger={false} total={count} onChange={this.changePage}  style={{ float: 'right', marginTop: 20 }}></Pagination>
                        </Col>
                    </Row>
                </Card>
                <AddModal
                    options={options} visible={showAdd} hideHandle={this.hideAdd} getList={this.getList}
                    searchSubject={searchSubject} currentPage={currentPage}
                />
                <EditModal
                    doc={doc} cover={cover} subjectValue={subjectValue} subject={subject}  sort={sort} name={name} id={id}
                    options={options} visible={showEdit} hideHandle={this.hideEdit} docs={docs} covers={covers}
                    changeSubject={this.changeSubject} changeInputValue={this.changeInputValue}
                    changeFile={this.changeFile} getList={this.getList}
                    searchSubject={searchSubject} currentPage={currentPage}is_jc={is_jc}
                />
            </PageContainer>
        );
    }
}

